<template>
  <div class="course-list"
       :class="type">
    <div class="search-box pof zi10 t0 w100"
         :class="'' + (isWx && showHeader)">
      <template v-if="type === 'video'">
        <div class="select-text flex tac">
          <span class="select-text-inner flex-1"
                @click="toggleSelect('grades')">{{currGrade.name || '全部年级'}}</span>
          <span class="select-text-inner flex-1"
                @click="toggleSelect('xuekeList')">{{xuekeObj.name || '全部学科'}}</span>
          <span class="select-text-inner flex-1"
                @click="toggleSelect('press')">{{pressObj.short_name || '全部出版社'}}</span>
        </div>
        <div class="select-box poa w100 l0"
             v-show="showSelect"
             @click="toggleSelect">
          <div class="select-box-inner ova">
            <div class="select-item"
                 @click="selectItem(item)"
                 :class="{active: item.id === currSelect.id}"
                 v-for="(item, i) in selectOption"
                 :key="i">
              {{item.name}}
            </div>
          </div>
        </div>
      </template>
      <template v-else-if="type === 'audio'">
        <div class="audio-select flex"
             v-for="(options, i) in audioSelect"
             :key="i">
          <div class="audio-select-option transition"
               :class="{active: !options.value.id,'wx-select':isWx}"
               @click="checkSelect(options, {})">
            全部
          </div>
          <div class="flex-1 ova">
            <div class="wsnw">
              <div class="audio-select-option transition dib vat"
                   :class="{active: options.value.id === opt.id,'wx-select':isWx}"
                   @click="checkSelect(options, opt)"
                   v-for="(opt, j) in options.list"
                   :key="j">
                {{opt.name}}
              </div>
            </div>
          </div>
        </div>
      </template>
    </div>
    <van-list class="list-inner"
              v-model="loading"
              :finished="finished"
              :offset="20"
              finished-text="没有更多了!"
              @load="loadMore">
      <course-card @btn-callback="btnCallBack"
                   @click-callback="itemCallBack"
                   :is-wx="isWx"
                   :type="type"
                   :item="item"
                   v-for="(item, i) in list"
                   :key="i"></course-card>
    </van-list>
  </div>
</template>

<script>
import { mapMutations, mapGetters } from 'vuex';

export default {
  name: 'CourseList',
  props: {
    showHeader: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      loading: true,
      finished: false,
      lockGet: true,

      limits: 10,
      total: 0,
      curr: 1,
      list: [],

      audioSelect: {
        age: { value: {}, list: [] },
        zhuanti: { value: {}, list: [] }
      },

      type: '',
      selectType: '',
      currSelect: {},
      showSelect: false,
      selectOption: [],

      xuekeList: [],
      press: [],
      xuekeObj: {},
      pressObj: {}
    };
  },
  computed: {
    ...mapGetters([
      'grades',
      'xueKe',
      'currGrade',
      'userInfo',
      'productInfo',
      'hasAudio',
      'isWx'
    ])
  },
  watch: {
    $route(route) {
      this.initPage();
    },
    xuekeObj(now, old) {
      this.press = [
        {
          id: '',
          name: '全部出版社'
        },
        ...now.press
      ];
      if (!this.press.find(e => e.id === this.pressObj.id)) {
        this.pressObj = this.press[0];
      }
      this.getList(true);
    }
  },
  created() {
    if (!this.hasAudio) {
      return this.$router.replace('/notchannel');
    }
    this.initPage();
  },
  methods: {
    ...mapMutations(['setCurrGrade', 'setXueKe']),

    getTagsList() {
      this.http
        .$post('api/resource.tag/get_type', {
          type_id: 7
          // pid: 343
        })
        .then(res => (this.audioSelect.age.list = res))
        .catch(console.log);
      this.http
        .$post('api/resource.tag/get_type', {
          type_id: 9,
          pid: 343
        })
        .then(res => (this.audioSelect.zhuanti.list = res))
        .catch(console.log);
    },

    checkSelect(opt, item) {
      if (opt.value.id !== item.id) {
        opt.value = item;
        this.getList(true);
      }
    },

    btnCallBack(item, stop) {
      if (this.type === 'video') {
        // [取消]收藏
        stop();
        this.http
          .$post('api/user/save_course_collection', {
            ...this.productInfo,
            uid: this.userInfo.uid,
            course_id: item.id
          })
          .then(() => {
            item.is_collection = +!item.is_collection;
          })
          .catch(console.log);
      } else {
        // 收听
      }
    },
    itemCallBack(item) {
      if (this.type === 'video') {
        // 视频
        this.$router.push('/classdetail/' + item.id);
      } else {
        // 音频
        this.$router.push('/audiodetail/' + item.id);
      }
    },

    loadMore() {
      if (this.lockGet) return;
      this.lockGet = true;
      this.curr++;
      this.getList();
    },

    getList(init) {
      if (init) {
        this.curr = 1;
      }
      let {
        type,
        curr,
        limits,
        currGrade,
        xueKe,
        pressObj,
        userInfo,
        audioSelect
      } = this;
      let url = 'api/resource.course/get_course_list';
      let params = {
        curr,
        limits,
        user_id: userInfo.uid,
        is_https: 1,
        xueke_id: xueKe,
        xueduan_id: currGrade.section,
        press_id: pressObj.id,
        module_id: 98, // 只要同步名师视频
        nianji_id: currGrade.section !== 4 ? currGrade.id : ''
      };
      if (type === 'audio') {
        url = 'api/resource.course/get_jd_course_list';
        params = {
          curr,
          limits,
          uid: userInfo.uid,
          is_https: 1,
          module_id: 343,
          age_id: audioSelect.age.value.id,
          zhuanti_id: audioSelect.zhuanti.value.id
        };
      }
      this.http
        .$post(url, params)
        .then(res => {
          if (curr === 1) {
            this.total = 0;
            this.list = [];
          }
          this.list.push(
            ...res.list.map(e => {
              e.name = e.name.split(/[:：]/);
              e.name = e.name[1] || e.name[0];
              return e;
            })
          );
          this.total = res.total;
        })
        .catch(err => {
          +err.code === 404 || this.$err(err);
        })
        .finally(() => {
          this.lockGet = false;
          this.loading = false;
          setTimeout(() => {
            this.finished = this.total <= this.list.length;
          }, 200);
        });
    },

    initPage() {
      this.type = this.$route.params.type;
      if (this.type === 'audio') {
        document.title = '有声专区';
        this.getTagsList();
        this.getList(true);
      } else {
        document.title = '同步课程';
        this.getXuekeList();
      }
    },
    //获取学科列表
    getXuekeList() {
      this.http
        .$post('api/resource.tag/get_tag', {
          nianji_id: this.currGrade.section !== 4 ? this.currGrade.id : '',
          xueduan_id: this.currGrade.section,
          module_id: 98
        })
        .then(res => {
          this.xuekeList = res.subjects.filter(e => e.id !== 38);
          let item = this.xuekeList.find(e => e.id === this.xueKe) ||
            this.xuekeList[0] || { id: '' };
          this.setXueKe(item.id);
          this.xuekeObj = item;
          // this.getIndexPageInfo(this.curr !== 1);
        })
        .catch(console.log);
    },
    toggleSelect(type) {
      if (type !== this.selectType && typeof type === 'string') {
        this.selectType = type;
        switch (type) {
          case 'grades':
            this.currSelect = this.currGrade;
            break;
          case 'xuekeList':
            this.currSelect = this.xuekeObj;
            break;
          case 'press':
            this.currSelect = this.pressObj;
            break;
        }
        this.selectOption = this[type] || [];
        this.showSelect = true;
      } else {
        this.selectType = '';
        this.showSelect = false;
      }
    },
    selectItem(item) {
      switch (this.selectType) {
        case 'grades':
          this.setCurrGrade(item);
          this.getXuekeList();
          break;
        case 'xuekeList':
          this.setXueKe(item.id);
          this.xuekeObj = item;
          break;
        case 'press':
          this.pressObj = item;
          this.getList(true);
          break;
      }
    }
  }
};
</script>

<style scoped lang="less">
.course-list {
  padding-top: 2.78rem;
  &.audio {
    padding-top: 6.13rem;
  }
}

.audio-select {
  padding: 0.94rem 0.94rem 0;
  font-size: 0.81rem;
  line-height: 1.75rem;
  & + .audio-select {
    padding-top: 0.75rem;
  }
  &:last-child {
    padding-bottom: 0.94rem;
  }
  &-option {
    padding: 0 0.94rem;
    border-radius: 1.75rem;
    color: #999;
    background-color: transparent;
    &.active {
      background-color: #f7f7f7;
      color: #ff850b;
      &.wx-select {
        color: #17cff8;
      }
    }
  }
}

.search-box {
  box-shadow: 0 0.03rem 0 0 rgba(0, 0, 0, 0.08);
  border-bottom: 0.03rem solid #e8e8e8;
  background-color: #fff;
  &.true {
    top: 3.75rem;
  }
}

.select-text {
  line-height: 2.75rem;
  font-size: 0.88rem;
  color: #999;
  &-inner {
    &:after {
      content: '';
      display: inline-block;
      margin: 0.22rem 0 0 0.22rem;
      vertical-align: middle;
      border: 0.3rem transparent solid;
      border-top-color: #999;
      transform-origin: center 25%;
      transition: transform 0.3s;
      /*transform: rotate(180deg);*/
    }
  }
}

.select-box {
  height: calc(100vh - 2.78rem);
  background-color: rgba(0, 0, 0, 0.3);
  &-inner {
    max-height: 16.59rem;
    background-color: #fff;
  }
  .select-item {
    padding-left: 1.28rem;
    line-height: 2.75rem;
    font-size: 0.88rem;
    color: #666;
    &:not(:last-child) {
      border-bottom: 0.03rem solid #e8e8e8;
    }
    &.active {
      color: #ff850b;
      background-color: #f4f4f4;
    }
  }
}

.list-inner {
  padding: 0.94rem;
}

.course-card {
  + .course-card {
    margin-top: 1rem;
  }
}
</style>
